package com.weiz.controller.excel;
import org.springframework.core.io.ClassPathResource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URLEncoder;
@RestController
public class Excel2Util {
    @GetMapping("/dist/{id}")
    public ResponseEntity<byte[]>  getUserById(@PathVariable String id) throws IOException {
        String templatePath = "model/"+id;
        ClassPathResource resource = new ClassPathResource(templatePath);
        InputStream inputStream = resource.getInputStream();
        byte[] data = innerInputStreamToByteArray(inputStream);
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
        headers.setContentDispositionFormData("attachment", URLEncoder.encode(id, "UTF-8"));
        return new ResponseEntity<>(data, headers, HttpStatus.OK);
    }
    public static byte[] innerInputStreamToByteArray(InputStream inputStream) throws IOException {
        ByteArrayOutputStream buffer = new ByteArrayOutputStream();
        int nRead;
        byte[] data = new byte[1024];
        while ((nRead = inputStream.read(data, 0, data.length))!= -1) {
            buffer.write(data, 0, nRead);
        }
        return buffer.toByteArray();
    }
}